﻿using DG.Tweening;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace UI.ExamplePanel
{
    /// <summary>
    /// 特殊卡牌选择面板（支持多个guest阶段）
    /// </summary>
    public class SelectSpecialCardPanel : BasePanel<SelectSpecialCardPanel>
    {
        public Material grayMaterial;
        public int guestIndex = 0; // 当前角色阶段：0柔歌, 1V
        public List<string> guestList = new List<string>();

        //动画切换影响相关UI
        public GameObject selectCardPanel;
        public GameObject selectEmoPanel;

        //三张卡的ui相关
        private List<Button> cardBtns = new List<Button>();
        private List<Image> cards = new List<Image>();
        private List<bool> isChosen = new List<bool>() { false, false, false };     //记录每张卡是否都被选择

        //展示卡牌
        private Image card;
        private Vector2 cardTargetPos = new Vector2(383, 0);        //动画位移用
        private float cardOrlSize = 2.14f;                          //动画缩放用
        private TextMeshProUGUI info;

        private List<Button> emoBtns = new List<Button>();
        private List<Image> emos = new List<Image>();
        private int currentCardIndex;

        public override void Init()
        {
            base.Init();

            // 缓存按钮和卡牌图片引用
            cardBtns.Clear();
            cardBtns.Add(GetControl<Button>("Card1"));
            cardBtns.Add(GetControl<Button>("Card2"));
            cardBtns.Add(GetControl<Button>("Card3"));

            cards.Clear();
            cards.Add(GetControl<Image>("Card1"));
            cards.Add(GetControl<Image>("Card2"));
            cards.Add(GetControl<Image>("Card3"));

            emoBtns.Clear();
            emoBtns.Add(GetControl<Button>("Emo1"));
            emoBtns.Add(GetControl<Button>("Emo2"));
            emoBtns.Add(GetControl<Button>("Emo3"));

            emos.Clear();
            emos.Add(GetControl<Image>("Emo1"));
            emos.Add(GetControl<Image>("Emo2"));
            emos.Add(GetControl<Image>("Emo3"));

            card = GetControl<Image>("EmoCard");
            info = GetControl<TextMeshProUGUI>("Thing");

            guestList.Clear();
            foreach(var character in StoryCardManager.Instance.GetAllCharacterNames())
            {
                guestList.Add(character);
            }

            // 每张卡单独克隆独立材质，避免共享
            foreach (var img in cards)
            {
                var mat = Instantiate(grayMaterial);
                img.material = mat;
            }


            SetCardSprites();
            RegisterCardClickEvents();
        }

        /// <summary>
        /// 初始化表情选项
        /// </summary>
        /// <param name="cardIndex"></param>
        public void InitEmoPanelData(int cardIndex)
        {
            //切换
            selectCardPanel.SetActive(false);
            selectEmoPanel.SetActive(true);

            currentCardIndex = cardIndex;

            foreach (var btn in emoBtns)
            {
                btn.onClick.RemoveAllListeners();
                btn.gameObject.SetActive(true);
            }

            string currentGuest = guestList[guestIndex];

            // 读取emoji路径
            var emojiPathList = StoryCardManager.Instance.GetCharacterStory(currentGuest).emojiPaths;

            for (int i = 0; i < emojiPathList.Count; i++)
            {
                emos[i].sprite = Resources.Load<Sprite>(emojiPathList[i]);
            }

            info.text = StoryCardManager.Instance.GetCardsForCharacter(currentGuest)[cardIndex].description;
            card.sprite = cards[cardIndex].sprite;

            // 注册点击事件
            for (int i = 0; i < emoBtns.Count; i++)
            {
                int idx = i;
                emoBtns[i].onClick.AddListener(() =>
                {
                    OnEmotionSelected(idx);
                });
            }
        }

        /// <summary>
        /// 设置三张卡的图片
        /// </summary>
        private void SetCardSprites()
        {
            if (guestIndex >= guestList.Count) return;

            // 初始化为灰化状态
            foreach (var img in cards)
            {
                img.material.SetFloat("_GrayAmount", 1f);
            }

            // 获取当前角色
            string currentGuest = guestList[guestIndex];
            var cardDatas = StoryCardManager.Instance.GetCardsForCharacter(currentGuest);

            if (cardDatas == null || cardDatas.Count == 0)
            {
                Debug.LogError($"未找到角色 {currentGuest} 的卡牌数据！");
                return;
            }

            // 按顺序设置贴图
            for (int i = 0; i < cards.Count; i++)
            {
                if (i >= cardDatas.Count) break;
                var path = cardDatas[i].path;
                cards[i].sprite = Resources.Load<Sprite>(path);
            }
        }

        /// <summary>
        /// 注册三张卡的点击事件
        /// </summary>
        private void RegisterCardClickEvents()
        {
            for (int i = 0; i < cardBtns.Count; i++)
            {
                int index = i;
                cardBtns[i].onClick.RemoveAllListeners();
                cardBtns[i].onClick.AddListener(() =>
                {
                    OnCardClicked(index);
                });
            }
        }

        /// <summary>
        /// 点击卡牌后打开选择面板
        /// </summary>
        private void OnCardClicked(int index)
        {
            if (isChosen[index])
            {
                return;
            }

            //可以做切换动画

            InitEmoPanelData(index);

        }

        /// <summary>
        /// 按钮选择回调：选择正确后调用
        /// </summary>
        public void OnCardSelectionFinished(int cardIndex)
        {
            if (cardIndex < 0 || cardIndex >= cards.Count) return;

            // 动画从灰到彩
            cards[cardIndex].material.DOFloat(0f, "_GrayAmount", 1f).SetEase(Ease.OutQuad);

            isChosen[cardIndex] = true;
            cardBtns[cardIndex].interactable = false; // 禁用该按钮

            // 检查是否全部完成
            if (AllChosen())
            {
                StartNextPhase();
            }
        }

        private bool AllChosen()
        {
            foreach (bool chosen in isChosen)
            {
                if (!chosen)
                    return false;
            }
            return true;
        }

        private void StartNextPhase()
        {
            StartCoroutine(WaitPanelEnd());
            //if (guestIndex < guestList.Count)
            //{
            //    // 下一阶段重新显示
            //    ResetForNextGuest();
            //    ShowMeNew();
            //}
            //else
            //{
            //    // 结束
            //    GamePanel.Instance.ShowMeNew();
            //}
        }

        private void ResetForNextGuest()
        {
            for (int i = 0; i < isChosen.Count; i++)
            {
                isChosen[i] = false;
                cardBtns[i].interactable = true;
            }

            SetCardSprites();
        }

        //有问题
        private void OnEmotionSelected(int index)
        {
            Debug.Log($"选择了第 {index + 1} 个情绪");
            emoBtns[index].gameObject.SetActive(false);

            System.Action callback = null;
            callback = () =>
            {
                DialogManager.Instance.OnDialogueFinished -= callback;

                // 判断是否选对
                if (index == currentCardIndex)
                {
                    //切换
                    selectCardPanel.SetActive(true);
                    selectEmoPanel.SetActive(false);
                    OnCardSelectionFinished(currentCardIndex);
                }
            };

            string guest = guestList[guestIndex] + currentCardIndex;
            DialogManager.Instance.OnDialogueFinished += callback;
            //这里传入的index应该是对错卡号，暂时先1，2，3顺序吧
            DialogManager.Instance.StartDialogueForCharacter(guest, index, transform);
        }

        private IEnumerator WaitPanelEnd()
        {
            yield return new WaitForSeconds(1.5f);
            Debug.Log("全部选择完成，进入下阶段。");
            guestIndex++;
            ResetForNextGuest();
            HideMe();

            //再次进入游戏阶段
            GamePanel.Instance.ShowMe();
            CoroutineManager.Instance.ForceStart(CoreMechanismManager.Instance.EnterGuest());
        }
    }
}
